package pkg

import (
	"bunker/pkg/pb"
	"context"
	"fmt"
	"log"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/protobuf/proto"
)

type Client struct {
	key  []byte
	conn *grpc.ClientConn
	c    pb.BunkerClient
	sign *Sign
}

func NewClient(socketPath string, key []byte) *Client {
	// 使用 Unix 域套接字连接，并禁用传输层的加密验证
	conn, err := grpc.NewClient("unix://"+socketPath, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}

	// 你的 gRPC 客户端逻辑
	client := pb.NewBunkerClient(conn)

	return &Client{
		key:  key,
		conn: conn,
		c:    client,
	}
}

func (sf *Client) SavaFile(fileName string, fileContent []byte, force bool) error {
	data := &pb.Data_SaveFile{
		Timestamp:   time.Now().Unix(),
		FileName:    fileName,
		FileContent: fileContent,
		Force:       force,
	}

	b, err := proto.Marshal(data)
	if err != nil {
		return err
	}

	req := &pb.Request{
		Sign: sf.sign.Sign(sf.key, b),
		Data: b,
	}

	rep, err := sf.c.SaveFile(context.Background(), req)
	if err != nil {
		return err
	}
	if rep.Code != 0 {
		return fmt.Errorf("save file failed: %s", rep.Message)
	}

	return nil
}

func (sf *Client) Close() {
	sf.conn.Close()
}
